<template>
	<view class="seckill-container">
        <view class="tabs-view">
            <tabs :list="timeLines" :seckillTime="true" bar-width="80" font-size="36" :seclill-time="true" name="time_text" :is-scroll="timeLines.length > 4 ? true : false" :current="timeLineIndex" active-color="#ff5000" @change="handleClickTimeLine"></tabs>
            <u-line></u-line>
            <view v-if="timeLines" class="seckill-times-view u-flex u-row-between">
                <view class="buy-txt" :class="selectTimeLine.distance_time ? 'no-start' : ''">{{ selectTimeLine.distance_time == 0 ? '抢购中' : '即将开始' }} 先下单先得哦</view>
                <view class="seckill-times">
                    <text class="seckill-nth">{{selectTimeLine.distance_time == 0 ? (onlyOne ? '距结束' : '距下轮开始') : '距开始'}}</text>
                    <text class="seckill-time">{{ selectTimeLine.hours }}:{{ selectTimeLine.minutes }}:{{ selectTimeLine.seconds }}</text>
                </view>
            </view>
        </view>
        <view class="goods-container">
            <mescroll-body ref="mescrollRef" top="140" @init="mescrollInit" :down="down" :up="up" @down="downCallback" @up="upCallback">
                <view v-for="(goods, index) in goodsList" :key="index" class="goods-item u-flex">
                    <navigator hover-class="none" class="goods-img" :url="'/goods-module/goods?goods_id=' + goods.goods_id + '&sku_id=' + goods.sku_id">
                        <image class="img" :src="goods.goods_image"></image>
                    </navigator>
                    <view class="u-flex-1" >
                        <view class="u-line-2 u-m-b-60">
                            {{ goods.goods_name }}
                        </view>
                        <view class="u-flex">
                            <view class="u-flex-1">
                                <custom-price :price="goods.seckill_price" :size="36" :fontWeight="600"></custom-price>
                                <view class=".original-price goods-org-price">￥{{ goods.original_price }}</view>
                            </view>
                            <view class="">
                                <text class="to-seckill-btn" v-if="seckillIsStart" @click="onGoodsDetail(goods.goods_id, goods.sku_id)">
                                    立即抢购
                                </text>
                                <text class="to-seckill-btn" v-else>
                                    即将开始
                                </text>
                            </view>
                        </view>
                    </view>
                </view>
            </mescroll-body>
        </view>
        <loading-view v-if="loading"></loading-view>
	</view>
</template>

<script>
    import * as API_Promotions from '@/api/promotions.js'
    import { Foundation } from '@/ui-utils'
    import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js"
	export default {
        mixins: [MescrollMixin],
		data() {
			return {
                timeLines: [],
                timeLineIndex: 0,
                selectTimeLine: {
                    distance_time: 0,
                    hours: '00',
                    minutes: '00',
                    seconds: '00'
                },
                times: [],
                timesText: [],
                goodsList: [],
                params: {
                  page_no: 1,
                  page_size: 10
                },
                onlyOne: false,
                down: {
                    auto: false //是否在初始化完毕之后自动执行一次下拉刷新的回调
                },
                up: {
                    auto: false
                },
                loading: true,
                interval: '',
			};
		},
        computed: {
            // 获取当前选中的时间节点是否开始
            seckillIsStart() {
                if(this.timeLines && this.timeLines.length) {
                    return this.timeLines.filter(item => item)[this.timeLineIndex].distance_time == 0
                }
            }
        },
        onLoad() {
          this.params.page_no = 1;
          this.getSeckillTimeLine();
        },
        /**
         * onHide()在小程序生命周期中具有监听小程序隐藏的功能，当切换页面和切换底部菜单栏时将会关闭定时器。
         */
        onHide() {
            clearInterval(this.interval)
        },
        /**
         * 生命周期函数--监听页面卸载，当切换页面和切换底部菜单栏时也会关闭定时器。
         */
        onUnload() {
            clearInterval(this.interval)
        },
        methods: {
            // 选中时刻
            selectedTimeLine() {
                this.selectTimeLine = {
                    distance_time: this.timeLines[this.timeLineIndex].distance_time,
                    hours: this.timesText[this.timeLineIndex].hours,
                    minutes: this.timesText[this.timeLineIndex].minutes,
                    seconds: this.timesText[this.timeLineIndex].seconds
                }
            },
            //上拉加载数据
            upCallback(page){
                this.params.page_no = page.num;
                this.getSeckillTimeLine();
            },
            //下拉刷新
            downCallback(){
                this.handleClickTimeLine(this.timeLineIndex);
            },
            //获取时间线
            getSeckillTimeLine() {
                API_Promotions.getSeckillTimeLine().then(response => {
                    if (!response || !response.length) {
                        uni.showModal({
                            content: '暂时还没有限时抢购正在进行，去别处看看吧！',
                            showCancel: false,
                            success: (res) => {
                                if(res.confirm) {
                                    uni.switchTab({
                                        url:'/pages/tabs/home/home'
                                    })
                                }
                            }
                        })
                        return false
                    }
                    response = response.sort((x, y) => (Number(x.time_text) - Number(y.time_text)))
                    response = response.slice(0, 5)
                    this.params.range_time = response[0].time_text
                    const times = []
                    const timesText = []
                    const onlyOne = response.length === 1

                    this.onlyOne = onlyOne
                    response.map((item, index) => {
                        const nextIndex = index + 1 < response.length ? index + 1 : response.length - 1
                        item.active = index === 0
                        if (item.distance_time == 0 && index === 0) {
                          if (onlyOne) {
                            times.push(Foundation.theNextDayTime())
                          } else {
                            times.push(response[nextIndex].distance_time)
                          }
                        } else {
                          times.push(item.distance_time)
                        }
                        timesText.push({ hours: '00', minutes: '00', seconds: '00' })
                        return item
                    })
                    this.times = times
                    this.timesText = timesText
                    this.timeLines = response
                    this.startCountDown()
                    this.getSeckillTimeGoods()
                })
            },
            // 开始倒计时
            startCountDown() {
                this.interval = setInterval(() => {
                    console.log('限时抢购倒计时.......')
                    const { times, timesText } = this
                    for (let i = 0; i < times.length; i ++) {
                        if (i === 0 && times[i] === 0) {
                            clearInterval(this.interval)
                            uni.showModal({
                                content: '新的限时抢购开始啦，请确认查看！',
                                showCancel: false,
                                success: (res) => {
                                    if (res.confirm) {
                                        this.params.page_no = 1;
                                        this.getSeckillTimeLine();
                                        console.log('用户点击确定');
                                    } else if (res.cancel) {
                                        console.log('用户点击取消');
                                    }
                                }
                            })
                            break
                        }
                        times[i] -= 1
                        const timeText = Foundation.countTimeDown(times[i])
                        this.$set(this.timesText, i, Foundation.countTimeDown(times[i]))
                    }
                    this.$set(this, 'times', times)
                    this.selectedTimeLine();
                }, 1000)
            },
            //时间段被选中
            handleClickTimeLine(index) {
                this.timeLineIndex = index
                this.goodsList = []
                this.params.page_no = 1
                const timeLine = this.timeLines[index]
                this.params.range_time = timeLine.time_text
                this.getSeckillTimeGoods()
            },
            //获取对应时刻的商品
            getSeckillTimeGoods() {
                API_Promotions.getSeckillTimeGoods(this.params).then(response => {
                    const { data } = response
                    this.goodsList.push(...data)
                    this.loading = false
                    this.mescroll.endBySize(data.length, response.data_total)
                })
            },
            onGoodsDetail(goodsId, skuId){
                uni.navigateTo({
                    url: '/goods-module/goods?goods_id=' + goodsId + '&sku_id=' + skuId
                })
            },
        }
	}
</script>

<style lang="scss">
    .seckill-container {
        .seckill-times-view {
            padding: 10rpx 30rpx;
            background: #FFFFFF;
            .buy-txt {
                // color: #FA3534;
                &.no-start {
                    color: #333333 !important;
                }
            }
            .seckill-times {
                font-size: 22rpx;
                .seckill-nth {
                    color: #fff;
                    padding: 4rpx 10rpx;
                    border-top-left-radius: 30rpx;
                    border-bottom-left-radius: 30rpx;
                    background-color: #ff5000;
                    border: 2rpx solid #ff5000;
                }
                .seckill-time {
                    color: #ff5000;
                    font-weight: 600;
                    padding: 4rpx 10rpx;
                    border-top-right-radius: 30rpx;
                    border-bottom-right-radius: 30rpx;
                    border: 2rpx solid #ff5000;
                }
            }
        }
        .goods-container {
            background-color: #FFFFFF;
            /deep/.u-empty {
                margin-top: 120rpx !important;
            }
            .goods-list {
                height: calc(100vh - 80rpx);
            }
            .goods-item {
                padding: 20rpx;
                border-bottom: 2rpx solid #E4E7Ed;
                .goods-img {
                    width: 200rpx;
                    height: 200rpx;
                    margin-right: 20rpx;
                    border-radius: 10rpx;
                    overflow: hidden;
                    .img {
                        width: 100%;
                        height: 100%;
                    }
                }
                .original-price {
                    text-decoration: line-through;
                    color: #848689;
                    font-size: 24rpx;
                }
                .to-seckill-btn {
                    color: #FFFFFF;
                    padding: 8rpx 20rpx;
                    border-radius: 8rpx;
                    background-color: #ff5000;
                }
                .goods-org-price {
                  font-size: 14px;
                  color: #82848a;
                  text-decoration: line-through;
                }
            }
        }
    }
</style>
